package cn.tedu.csmall.passport.security;

import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.pojo.vo.AdminLoginInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class UserDetailsServiceIpml implements UserDetailsService {
    @Autowired
    AdminMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AdminLoginInfoVO loginInfo = mapper.getLoginInfoByUsername(s);
        if(loginInfo==null) {
            return null;
        }


        List<String> permission = loginInfo.getPermission();
        Collection<GrantedAuthority> authorities=new ArrayList<>();
        for (String p: permission) {
            GrantedAuthority authority=new SimpleGrantedAuthority(p);
            authorities.add(authority);
        }



        AdminDetails userDetails=new AdminDetails(
                loginInfo.getId(),
                loginInfo.getUsername(),
                loginInfo.getPassword(),
                loginInfo.getEnable()==1,
                authorities
        );

//        UserDetails userDetails= User.builder()
//                //.id(loginInfo.getId())
//                .username(s)
//                .password(loginInfo.getPassword())
//                .accountExpired(false)
//                .accountLocked(false)
//                .disabled(loginInfo.getEnable()==0)
//                .credentialsExpired(false)
//                .authorities("暂时权限")
//                .build();
        return userDetails;
    }
}
